package com.webserver;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Processor extends Thread{
	
	private Socket socket;
	private InputStream is;
	private PrintStream ps;
	private final static String WEB_ROOT="D:\\htdocs";
	
	public Processor(Socket socket) {
		this.socket = socket;
		try {
			//获得输入流
			is=socket.getInputStream();
			ps=new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	//启动线程
	@Override
	public void run() {
		String fileName=parse(is);
		sendFile(fileName);
	}
	
	/***
	 * 输入输出流处理
	 * @param is
	 * @return 返回用户访问的资源名
	 */
	public String parse(InputStream is){
		String fileName="";
		//从http协议内容中获取用户需要访问哪个文件
		//由字节流变成字符流
		BufferedReader br =new BufferedReader(new InputStreamReader(is));
		try {
			String httpMessage=br.readLine();//http 第一行就是访问名称,它分为三个部分
			String[] content=httpMessage.split(" ");//一、协议的状态号 二、请求文件的名称三、协议的版本
			if(content.length!=3){//请求错误
				sendErrorMessage(400, "client query error!");
				return null;
			}
			System.out.println("code:"+content[0]+"||fileName:"+content[1]+"||http version:"+content[2]);
			fileName=content[1];
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fileName;
	}
	//发送错误信息，输出错误信息
	public void sendErrorMessage(int errorCode,String errorMessage){
		ps.println("HTTP/1.0 "+errorCode+" "+errorMessage);
		ps.println("content-type: text/html");
		ps.println();
		ps.print("<html>");
		ps.print("<title>Error Message</title>");
		ps.print("<body>");
		ps.print("<h1>ErrorCode:"+errorCode+",ErrorMeaage:"+errorMessage+"</h1>");
		ps.print("</body>");
		ps.print("</html>");
		ps.flush();
		ps.close();
		try {
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	//发送正确信息/输出正确信息,返回资源
	public void sendFile(String fileName){
		File file =new File(this.WEB_ROOT+fileName);
		if(!file.exists()){	//判断文件是否存在
			sendErrorMessage(404, "File Not Found");
			return ;
		}
		try {
			//读取文件
			InputStream input=new FileInputStream(file);
			byte content[]=new byte[(int)file.length()];
			input.read(content);
			
			ps.println("HTTP/1.0 200 queryfile");//http 协议号 版本号
			ps.println("content-length:"+content.length);//返回长度or文件大小
			ps.println();//http协议结束
			
			//资源内容
			ps.write(content);
			ps.flush();
			ps.close();
			input.close();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}
